package com.chang.dp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chang.dp.daos.TaskDao;
import com.chang.dp.entity.TaskEntity;
import com.chang.dp.entity.UsersEntity;
import com.chang.dp.mappers.TaskMapper;
import com.chang.dp.mappers.UsersMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
@Api(tags = "任务模块")
@RequestMapping("/tasks")
public class TaskController {

    @Resource
    TaskDao taskDao;

    @Autowired
    TaskMapper taskMapper;

    @Autowired
    UsersMapper usersMapper;

    @RequestMapping(path = "/list", method = RequestMethod.POST)
    @ApiOperation(notes = "根据类型过滤", value = "分页查询任务列表")
    public HashMap getTaskListByPage(@RequestBody TaskEntity taskEntity) {
        HashMap result = new HashMap();

        QueryWrapper queryWrapper = new QueryWrapper<>(taskEntity);
        taskMapper.selectPage(taskEntity.getPagination(), queryWrapper);
        List<TaskEntity> list = taskDao.getTasksByPage(taskEntity);
        result.put("code", 200);
        result.put("message", "查询成功");
        result.put("data", list);

        return result;
    }

    @RequestMapping(path = "/create", method = RequestMethod.POST)
    @ApiOperation(notes = "新建任务", value = "新建任务")
    public HashMap createTask(@RequestBody TaskEntity taskEntity) {
        HashMap hashMap = new HashMap();
        taskMapper.insert(taskEntity);

        return hashMap;
    }

    @RequestMapping(path = "/edit", method = RequestMethod.POST)
    @ApiOperation(notes = "编辑任务", value = "编辑的时候id必传")
    public HashMap editTask (@RequestBody TaskEntity taskEntity) {
        HashMap result = new HashMap();
        taskMapper.updateById(taskEntity);

        return result;
    }

    @RequestMapping(path = "/detail/{id}", method = RequestMethod.GET)
    @ApiOperation("查询任务详情")
    public HashMap<String, Object> getTaskDetail (@PathVariable("id") int id) {
        HashMap<String, Object> result = new HashMap<>();
        TaskEntity taskEntity = taskMapper.selectById(id);
        try {
            UsersEntity usersEntity = new UsersEntity();
            usersEntity.setUserId(taskEntity.getCreatorId());
            UsersEntity creatorEntity = usersMapper.selectOne(new QueryWrapper<>(usersEntity));
            taskEntity.setCreator(creatorEntity);
        } catch (Exception e) {
            throw e;
        }
        result.put("message", "查询成功");
        result.put("code", 200);
        result.put("data", taskEntity);
        return result;
    }
}
